<template>
  <div>
    <a-form :model="formState" ref="userDept">
      <a-form-item name="deptIds">
        <a-transfer :dataSource="deptList" v-model="formState.deptIds" :listStyle="{ width: '45%', height: '480px' }" :titles="[' 可选部门', ' 已选部门']" :render="(item) => item.title" :target-keys="formState.deptIds" @change="handleTransferChange" filterable> </a-transfer>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" name="UserDept" setup>
import { ref, reactive } from 'vue'
import { getAuthDeptList, setUserDept } from '@/views/sys/user/data/user.api'
const userDept = ref()
const deptList = ref()
const userId = ref()
const formState = reactive({
  deptIds: [],
})

/**
 * 设置数据
 * @param data
 */
async function setData(data) {
  userId.value = data.record.userId
  getAuthDeptList({
    organizationId: data.record.organizationId,
    userId: userId.value,
  }).then((data) => {
    data.deptList.map((item) => {
      item.key = item.deptId
      item.title = item.deptName
    })
    deptList.value = data.deptList
    formState.deptIds = data.deptIds
  })
}

/**
 * 穿梭框change
 * @param targetKeys
 * @param direction
 * @param moveKeys
 */
function handleTransferChange(targetKeys, direction, moveKeys) {
  formState.deptIds = targetKeys
}

/**
 * 提交已分配部门
 */
async function handleSubmit(drawerEmit) {
  userDept.value.validate().then(() => {
    setUserDept({
      userId: userId.value,
      deptIds: formState.deptIds.join(','),
    })
  })
}

/**
 * 暴露给父组件调用的方法
 */
defineExpose({
  setData,
  handleSubmit,
})
</script>
